//
//  AboutViewController.m
//  SchoolProduct
//
//  Created by 蒋松涵 on 16/9/5.
//  Copyright © 2016年 sm. All rights reserved.
//

#import "AboutViewController.h"
//二维码
#import "ErWeiMaViewController.h"
//
#import "AppVersion.h"

@interface AboutViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>


@property(nonatomic,strong)UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * dataArray;
@property (nonatomic,retain) NSString *urlStr;
@property (nonatomic,retain) NSDictionary *urlParameters;

@property (nonatomic,strong) NSString * appID;

@property (nonatomic,strong) NSString * latestVersion;//最新版本
@property (nonatomic,strong) NSString * trackViewUrl;//地址
@property (nonatomic,strong) NSString * trackName;
@property (nonatomic,strong) NSString * currentVersion;//此应用版本号

@end

@implementation AboutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"关于校话";
    
    self.dataArray = [[NSMutableArray alloc]init];
    
    [self init_TableView];
    [self tableHeaderView];
}

#pragma mark - 表头
-(void)tableHeaderView
{
    CGFloat h = 736 / ScreenHeight;
    CGFloat w = 414 / ScreenWidth;
    
    
    UIView * _tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100/h)];
    _tableHeaderView.backgroundColor = [UIColor colorWithRed:174/255.0 green:209/255.0 blue:42/255.0 alpha:1];
    self.tableView.tableHeaderView = _tableHeaderView;
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 45)/2/w, (100 - 45)/2/h, 45/w, 45/h)];
    imageView.image = [UIImage imageNamed:@"8.30 新增图标导图-11.png"];
    [_tableHeaderView addSubview:imageView];
    
}


#pragma mark - TableView
-(void)init_TableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的表（线）
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    //禁止滑动
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    
}

#pragma mark - TableViewDataSource--------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //    CGFloat h = 736 / ScreenHeight;
    CGFloat w = 414 / ScreenWidth;
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    

    
    if (indexPath.row == 0)
    {
        cell.textLabel.text = @"检查新版本";
        cell.textLabel.font = [UIFont systemFontOfSize:17/w];
    }
    else if (indexPath.row == 1)
    {
        cell.textLabel.text = @"功能介绍";
        cell.textLabel.font = [UIFont systemFontOfSize:17/w];
    }
    else if (indexPath.row == 2)
    {
        cell.textLabel.text = @"使用建议反馈";
        cell.textLabel.font = [UIFont systemFontOfSize:17/w];
    }
    else if (indexPath.row == 3)
    {
        cell.textLabel.text = @"隐私声明";
        cell.textLabel.font = [UIFont systemFontOfSize:17/w];
    }
    else if (indexPath.row == 4)
    {
        cell.textLabel.text = @"版权信息";
        cell.textLabel.font = [UIFont systemFontOfSize:17/w];
    }
    else
    {
        cell.textLabel.text = @"校话二维码";
        cell.textLabel.font = [UIFont systemFontOfSize:17/w];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    AppVersion * model = self.dataArray[indexPath.row];
    //检查新版本
    if (indexPath.row == 0)
    {
//        [self init_AppVersion];
        
        //通过同步请求，解析json数据，得到了数据
        NSError * error;
        NSString * urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",self.appID];
        
        NSURL * url = [NSURL URLWithString:urlStr];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        
        NSData * response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSDictionary * appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        if (error)
        {
            NSLog(@"error: %@",[error description]);
        }
        NSArray * resultsArray = [appInfoDic objectForKey:@"appVersion"];
        if (![resultsArray count])
        {
            NSLog(@"error: resultsArray==nil");
        }
        
        NSDictionary * infoDic = [resultsArray objectAtIndex:0];
        //
        self.latestVersion = [infoDic objectForKey:@"version"];
        self.trackViewUrl = [infoDic objectForKey:@"url"];
        self.trackName = [infoDic objectForKey:@"name"];
        
        //获取此应用的版本号
        NSDictionary * infoDict = [[NSBundle mainBundle] infoDictionary];
        
        self.currentVersion = [infoDict objectForKey:@"version"];
        
        double doubleCurrentVersion = [self.currentVersion doubleValue];
        double doubleUpdateVersion = [self.latestVersion doubleValue];
        
        //两个点，最后哪个是无效的
        if (doubleCurrentVersion < doubleUpdateVersion)
        {
            NSString * titleStr = [NSString stringWithFormat:@"检查更新: %@",self.trackName];
            NSString * messageStr = [NSString stringWithFormat:@"发现新版本（%@），是否更新？",self.latestVersion];
            
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:titleStr message:messageStr delegate:self cancelButtonTitle:@"暂不更新" otherButtonTitles:@"更新", nil];
            alert.tag = [self.appID intValue];
            [alert show];
        }
        else
        {
            NSString * titleStr = [NSString stringWithFormat:@"检查更新: %@",self.trackName];
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:titleStr message:@"暂无新版本" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
            alert.tag = [self.appID intValue] + 1;
            [alert show];
        }
    }
    else if (indexPath.row == 1)
    {
        //功能介绍
    }
    else if (indexPath.row == 2)
    {
        //使用建议反馈
    }
    else if (indexPath.row == 3)
    {
        //隐私声明
    }
    else if (indexPath.row == 4)
    {
        //版权信息
    }
    else
    {
        //校话二维码
        self.hidesBottomBarWhenPushed = YES;
        ErWeiMaViewController * erweimaVC = [[ErWeiMaViewController alloc]init];
        [self.navigationController pushViewController:erweimaVC animated:YES];
    }

}

#pragma mark - 检查版本更新---------
-(void)init_AppVersion
{
    _urlStr = @"http://www.100xsys.com.cn/school/app/commonAccoutInfo/getAppVersionInfo";
    _urlParameters = [[NSDictionary alloc]initWithObjectsAndKeys:@"ios",@"appVersion.type", nil];
    [self fecthDataFromNet:_urlStr parameters:_urlParameters];
}
//请求数据
- (void)fecthDataFromNet:(NSString *)url parameters:(NSDictionary *)parameter {
    
    NSLog(@"%@",url);
    NSLog(@"%@",parameter);
    //初始化请求工具
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        //        NSLog(@"登录-%@",dic[@"message"]);
        NSLog(@"APP版本-%@",dic);
        AppVersion * appM = [[AppVersion alloc]init];
        [appM setValuesForKeysWithDictionary:dic[@"appVersion"]];
        
        NSLog(@"%@",appM);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        
    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == [self.appID intValue])
    {
        if (buttonIndex == 1)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.trackViewUrl]];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
